package controller

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"runtime/debug"
	"smart_home/task/models"
	"smart_home/task/system"
	"tools"
)

func GetTrip() error {
	ls := models.GetTrip()
	for _, v := range ls {
		go system.Producter(v, DelTrip)
	}
	return nil
}

func DelTrip(data interface{}) {
	// 捕抓错误 防止mqtt客户端死掉
	defer func() {
		if err := recover(); err != nil {
			logs.Error("panic error:", err)
			debug.PrintStack()
		}
	}()

	var (
		trip           *models.Trip
		user           *models.User
		err            error
		title, content string
	)

	title = "行程通知"
	trip = data.(*models.Trip)
	fmt.Println(trip)
	if trip.UserId == trip.To { // 提醒自己
		content = "行程提醒: " + trip.What + "【" + trip.Time + "】"
	} else {
		if user, err = models.GetUserById(trip.UserId); err != nil {
			logs.Error("DelTrip error:", err)
			return
		}
		content = user.NickName + "对您说:" + trip.Time + trip.What

		selfMsg := "已提醒" + trip.ToUser.NickName + ", " + trip.Time + trip.What

		// 推送
		err = tools.NewJpush().SetAlias(trip.UserId).SetAlert(selfMsg).Jump("message").Send()
		if err != nil {
			logs.Error(err)
		}

		// 记录日志
		models.AddMessage(trip.UserId, title, selfMsg)
	}

	// 完成
	if trip.Wkocc == "0000000" {
		models.SetTripFinish(trip)
	}

	err = tools.NewJpush().SetAlias(trip.To).SetAlert(content).Jump("message").Send()
	if err != nil {
		logs.Error(err)
	}
	fmt.Println("err:", err)

	// 记录日志
	models.AddMessage(trip.To, title, content)
}
